import React, { useEffect, useState } from 'react'
import './style.less'
import { Button, Flex, Form, Popconfirm } from 'antd'
import { EMPTYTEXT, hsHandleTableDateTime, message, usePage } from '@hs-admin/utils'
import { useNavigate } from 'react-router-dom'
import { HsAdminTablePage, HsAdminForm, HsAdminSpin, HsAdminInput } from '@hs-admin/base-components'
import { dataItemStatus } from '@/utils/type'
import { getSettingAtlasList, publishSettingAtlas } from '@/api/setting/atlas'
import { HsAdminSelectDomain } from '@hs-admin/components'
import PublishPlatform from '@/components/PublishPlatform'
import { getAllPlatform } from '@hs-server/api'

const OperationIndustryAtlas: React.FC = () => {
  const navigate = useNavigate()
  const { pagination, resetPage }: { pagination: UsePageProps; resetPage: () => void } = usePage(callList)
  const [keywords, setkeywords] = useState(undefined)
  const [allPlatform, setallPlatform] = useState([])

  // 搜索和重置都会执行
  const handleSearch = () => {
    resetPage()
  }
  const [form] = Form.useForm()
  const formItemOptions = [
    {
      name: 'keywords',
      FormItemColProps: {
        span: 6
      },
      slot: 'keywords'
    },
    {
      label: '所属领域',
      name: 'domain_id',
      slot: 'domain_id',
      FormItemColProps: {
        span: 6
      }
    },
    {
      label: '发布平台',
      name: 'platform_id__in',
      component: 'Cascader',
      componentProps: {
        options: allPlatform,
        onChange: (_value: any, selectedOptions: any) => {
          const find: any = allPlatform.find((item: any) => item.value === selectedOptions.map((item: any) => item.value).join(','))
          //找到选中那一项 如果有children就不请求
          if (!find || !find?.children) {
            handleSearch()
          }
        },
        changeOnSelect: true
      },
      FormItemColProps: {
        span: 6
      },
      width: 350
    },
    {
      label: '发布状态',
      name: 'release_status',
      component: 'Select',
      componentProps: {
        options: dataItemStatus(),
        onChange: handleSearch
      },
      FormItemColProps: {
        span: 6
      }
    }
  ]
  const [data, setData] = useState<any[]>([])
  const [loading, setloading] = useState(true)

  const columns = [
    {
      title: '产业数仓名称',
      dataIndex: 'name'
    },
    {
      title: '关联图谱名称',
      dataIndex: 'map_name'
    },
    {
      title: '所属领域',
      dataIndex: 'industry_domain.name'
    },
    {
      title: '图谱ID',
      dataIndex: 'map_id'
    },
    {
      title: '发布状态',
      dataIndex: 'release_status',
      render: (_: any, record: any) => (
        <div>{record.release_info?.release_status ? dataItemStatus(record.release_info.release_status) : EMPTYTEXT}</div>
      )
    },
    {
      title: '发布/下线时间',
      dataIndex: 'updated_at',
      render: (_: any, record: any) => (
        <span>{record.release_info?.updated_at ? hsHandleTableDateTime(record.release_info.updated_at) : EMPTYTEXT}</span>
      )
    },
    {
      title: '发布平台',
      dataIndex: 'release_info',
      render: (_: any, record: any) => (
        <span>
          {record.release_info?.platforms?.length ? record.release_info.platforms.map((item: { name: any }) => item.name)?.join(',') : EMPTYTEXT}
        </span>
      )
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      fixed: 'right',
      render: (_: any, record: any) => {
        return actionCompute(record)
      }
    }
  ]
  const actionCompute = (record: any) => (
    <Flex gap={'middle'}>
      <Button type="link" size="small" onClick={() => callDetail(record)}>
        详情
      </Button>
      <Popconfirm
        description={
          <PublishPlatform
            type="IndustryChain"
            record={record}
            updateChecked={(checkedValue) => {
              record.checkedValue = checkedValue
            }}
          />
        }
        title=""
        trigger="click"
        icon=""
        onConfirm={async () => {
          setloading(true)
          publishSettingAtlas({ id: record.id, platforms: record.checkedValue?.filter((item: string | any[]) => item?.length) || [] })
            .then(() => {
              message.success('发布成功')
              callList()
            })
            .finally(() => {
              setloading(false)
            })
        }}>
        <Button type="link" size="small">
          发布
        </Button>
      </Popconfirm>
    </Flex>
  )

  // 详情
  function callDetail(record: any = {}) {
    navigate(`/setting/atlasDetail?id=${record.id || ''}`)
  }
  // 列表查询事件
  async function callList() {
    setloading(true)
    const fieldsValue = form.getFieldsValue()
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      ...fieldsValue,
      platform_id__in: fieldsValue.platform_id__in?.length ? fieldsValue.platform_id__in.at(-1) : null,
      keywords
    }
    const res = await getSettingAtlasList(params)
    const tableData = res.items ?? []
    setData(tableData)
    setloading(false)
    return res
  }

  useEffect(() => {
    getAllPlatform({ use_for: 'industry' }).then((res) => {
      setallPlatform(res)
    })
  }, [])

  return (
    <div className="operation-industry-atlas-page-wrapper">
      {loading && <HsAdminSpin />}
      <HsAdminForm form={form} formItemOptions={formItemOptions} labelCol={{ span: 8 }} wrapperCol={{ span: 15 }}>
        <div slot="domain_id">
          <HsAdminSelectDomain placeholder="请选择所属领域" onChange={handleSearch} />
        </div>
        <div slot="keywords">
          <HsAdminInput
            Search
            placeholder="请输入搜索内容"
            enterButton="搜索"
            onSearch={(value: React.SetStateAction<undefined>) => {
              setkeywords(value)
              handleSearch()
            }}
          />
        </div>
      </HsAdminForm>
      <HsAdminTablePage columns={columns} rowKey="id" dataSource={data} pagination={pagination} size="small"></HsAdminTablePage>
    </div>
  )
}

export default OperationIndustryAtlas
